"""
@File    :   excel2json.py
@Time    :   2024/02/28 16:22:31
@Author  :   glx 
@Version :   1.0
@Contact :   18095542g@connect.polyu.hk
@Desc    :   None
"""

# here put the import lib
import pandas as pd
import json
from typing import Dict, List


def time2str(time: pd.Timestamp):
    return time.strftime("%Y-%m-%d %H:%M:%S")


def build_ts_range(data: pd.DataFrame, step: int, start_time):
    ts_range = pd.date_range(start=start_time, periods=len(data), freq=f"{step}s")
    return ts_range


def trans_csv_json(csv_url: str, pattern: Dict[str, List[str]]):
    data = pd.read_csv(csv_url, header=None)
    signal = data[0].tolist()
    time = list(time2str(build_ts_range(data, 4, pd.Timestamp.today())))
    json_data = {"signal": signal, "time": time, "config": pattern["config"].copy()}
    return json_data


def trans_DATA_json(DATA: List, pattern: Dict[str, List[str]]):
    data = pd.DataFrame(DATA)
    signal = data[0].tolist()
    time = list(time2str(build_ts_range(data, 4, pd.Timestamp.today())))
    json_data = {"signal": signal, "time": time, "config": pattern["config"].copy()}
    return json_data


def trans_xls_json(csv_url, pattern: Dict[str, List[str]]):
    data = data = pd.read_csv(csv_url)
    data = data.to_dict(orient="records")
    signal = data
    time = [
        (
            data[i]["TS"]
            if isinstance(data[i]["TS"], str)
            else time2str(pd.Timedelta(data[i]["TS"], unit="s") + pd.Timestamp.today())
        )
        for i in range(len(data))
    ]
    json_data = {"signal": signal, "time": time, "config": pattern["config"].copy()}
    return json_data


if __name__ == "__main__":
    import os

    ## 1. excel to json
    # data_folder = "data"
    # json_folder = "data/json_data"

    # # Get all excel files in the data folder
    # excel_files = [
    #     file for file in os.listdir(data_folder) if file.endswith((".xlsx", ".xls"))
    # ]

    # # pattern
    # with open(r"data\pattern.json", "r") as f:
    #     pattern = json.load(f)

    # # Iterate over each excel file
    # for excel_file in excel_files:
    #     # Construct the file paths
    #     xls_url = os.path.join(data_folder, excel_file)
    #     json_file = os.path.splitext(excel_file)[0] + ".json"
    #     json_path = os.path.join(json_folder, json_file)

    #     # Execute trans_xls_json() method
    #     data = trans_xls_json(xls_url, pattern)

    #     # Save the result as JSON
    #     with open(json_path, "w") as f:
    #         json.dump(data, f, indent=4)

    ## 2. csv to json
    data_folder = r"data\csv"
    json_folder = "data/json_data"

    # Get all excel files in the data folder
    excel_files = [file for file in os.listdir(data_folder) if file.endswith((".csv"))]

    # pattern
    with open(r"data\pattern.json", "r") as f:
        pattern = json.load(f)

    # Iterate over each excel file
    for excel_file in excel_files:
        # Construct the file paths
        xls_url = os.path.join(data_folder, excel_file)
        json_file = os.path.splitext(excel_file)[0] + ".json"
        json_path = os.path.join(json_folder, json_file)

        # Execute trans_xls_json() method
        data = trans_csv_json(xls_url, pattern)

        # Save the result as JSON
        with open(json_path, "w") as f:
            json.dump(data, f, indent=4)
